package com.lzp.mybatis.custom.sqlsession.defaults;

import com.lzp.mybatis.custom.config.Configuration;
import com.lzp.mybatis.custom.sqlsession.SqlSession;
import com.lzp.mybatis.custom.sqlsession.proxy.MapperProxy;
import com.lzp.mybatis.custom.utils.DataSourceUtil;

import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * SqlSession接口实现类
 */
public class DefaultSqlSession implements SqlSession {

    // 主配置POJO类
    private Configuration config;
    private Connection connection;

    public DefaultSqlSession(Configuration config) {
        this.config = config;
        connection = DataSourceUtil.getConnection(config);
    }

    /**
     * 创建代理对象
     *
     * @param mapperClass 接口字节码
     * @return
     */
    @Override
    public <T> T getMapper(Class<T> mapperClass) {
        return (T) Proxy.newProxyInstance(
                mapperClass.getClassLoader(),
                new Class[]{mapperClass},
                new MapperProxy(config.getMappers(), connection));
    }

    /**
     * 释放SqlSession资源
     */
    @Override
    public void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
